const db = wx.cloud.database();
const app = getApp();
const httpUrl = "https://6875-huazai-6g820orq10216ac7-1316354189.tcb.qcloud.la/";
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
var messageArr = [];
var themeColorArr = {
    "愉悦": "#FAE2C0",
    "轻松": "#FDF3C0",
    "无语": "#D5ECD0",
    "发愁": "#D9D9F0",
    "崩溃": "#BCC9CF",
    "": "#FFFFFF"
};
var deepThemeColorArr = {
    "愉悦": "#FFA638",
    "轻松": "#FBEE69",
    "无语": "#ADDB89",
    "发愁": "#9AA8CB",
    "崩溃": "#373526",
    "": "#FFFFFF"
}
// var messageArr = [];
Page({

    /**
     * 页面的初始数据
     */
    data: {        
    },
    getPx(rpx) {
        let px;
        wx.getSystemInfo({
            success(res) {
                px = rpx * (res.windowWidth / 750);
            }
        })
        return Number(px);
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.updateMessages();
    },
    updateMessages(){
        let that = this;
        db.collection("messageDB").orderBy('createTime','desc').where({
            targetID: app.globalData.openid
        }).get({
            success: function(res) {
                messageArr = res.data;
                app.globalData.message = messageArr.length;
                for ( let i in res.data ) {
                    db.collection("infoDB").where({
                        _openid: res.data[i]._openid
                    }).get({
                        success: function(res) {
                            messageArr[i]["nickname"] = res.data[0].nickname;
                            if ( res.data[0].avatar )
                                messageArr[i]["avatar"] = res.data[0].avatar;
                            else
                                messageArr[i]["avatar"] = defaultAvatarUrl;
                            that.setData({
                                messageArr: messageArr
                            });
                        }
                    })
                    db.collection("diaryDB").doc(res.data[i].where).get({
                        success: function(res) {
                            messageArr[i]["color"] = themeColorArr[res.data.emoji];
                            if ( Object.keys(res.data.cloudPath).length > 0 ) {
                                for ( let j in res.data.cloudPath ) {
                                    messageArr[i]["previewImage"] = res.data.cloudPath[j];
                                    break;
                                }
                            }
                            else {
                                messageArr[i]["previewText"] = res.data.diary.substr(0,4);
                                messageArr[i]["previewTextColor"] = deepThemeColorArr[res.data.emoji]; 
                            }
                            
                            that.setData({
                                messageArr: messageArr
                            });
                        },
                        fail: function(res) {
                            messageArr[i]["color"] = "#888888";
                            messageArr[i]["previewText"] = "已删除"
                            messageArr[i]["previewTextColor"] = "#FFFFFF"
                            that.setData({
                                messageArr: messageArr
                            });
                        }
                    })
                }
                that.setData({
                    messageArr: messageArr
                });

            }
        })
    },
    loadAvatar(url){
        let file = url.substr(72,url.length);
        return httpUrl + file;
    },
    touchstart(e){
        if (this.data.isAnimation) {
            this.createAnimation(0)
        }
        this.setData({
            index: e.currentTarget.dataset.index,
            Xstart: e.changedTouches[0].pageX
        });
    },
    touchmove(e) {
        //  从右往左的移动距离 = 触摸初始位置x坐标 - 当前位置的x坐标
        let move = this.data.Xstart - e.changedTouches[0].pageX;
        // 当从右往左位移大于0px的时候 调用方法创建动画
        if (move > 0) {
            this.createAnimation(-move)
        } else {
            // 当从左往右滑动的时候将让卡片复位
            this.createAnimation(0)
        }
    },
    touchend(e) {
        let move = this.data.Xstart - e.changedTouches[0].pageX;
        // 当位移大于50px的时候认为展示删除按钮
        if (move > 50) {
            this.createAnimation(-160)
        } else {
            // 复位
            this.createAnimation(0)
        }
    },
    createAnimation(changeX) {
        if (messageArr.length > 0) {
            let ani = wx.createAnimation({
                delay: 0,
                timingFunction: 'ease',
            }).translateX(this.getPx(changeX)).step().export()
            console.log(this.data.index);
            messageArr[this.data.index].aniMation = ani
            this.setData({
                messageArr,
                isAnimation: true
            })
        }
    },
    deleteMessage(e){
        let that = this;
        this.createAnimation(0);
        let id = e.currentTarget.dataset.id;
        let index =  e.currentTarget.dataset.index;
        messageArr.splice(index,1);
        db.collection("messageDB").doc(id).remove();
        wx.showToast({
          title: '删除成功！',
          icon: 'none'
        })
        this.setData({
            messageArr,
            index: 0
        })

        app.globalData.message -= 1;
    },
    gotoDiary(e){
        let that = this;
        let where = e.currentTarget.dataset.where;
        let messageID = e.currentTarget.dataset.id;
        let index =  e.currentTarget.dataset.index;

        db.collection("diaryDB").doc(where).get({
            success: function(res) {
                let year = res.data.year;
                let month = res.data.month;
                let authorid = res.data._openid;
                let day = res.data.day;
                let emoji = res.data.emoji;
                let diary = res.data.diary;
                let id = res.data._id;
                let cloudPath = res.data.cloudPath;
                let timeString = res.data.createTime.valueOf();
                let images = [];
                for ( let j in res.data.cloudPath ) {
                    let url = res.data["cloudPath"][j];
                    let image = httpUrl + url.substr(72,url.length);
                    images.push(image);
                }
                that.setData({
                    messageArr,
                    index: 0
                })
                app.globalData.message -= 1; 
                wx.navigateTo({
                    url: '../diary/diary',
                    success: function(res) {
                        res.eventChannel.emit('acceptDataFromOpenerPage',{year:year,month:month,authorid:authorid,day:day,emoji:emoji,diary:diary,id:id,images:images,cloudimage:cloudPath,publish:false,fixmode: false,visit:true,timeString:timeString});
                    }
                })

            }
        })
        
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.updateMessages();
        setTimeout(function(){
            wx.stopPullDownRefresh();
        },1000);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})